import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    Platform,
    FlatList,
    DeviceEventEmitter
} from 'react-native';
import {Toast,ModalIndicator,Overlay} from 'teaset';
import Utils from '../common/Utils'
import NewsChatItem from "./NewChatItem";
import OverlaySureRemind from "../compoment/OverlaySureRemind";
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
import mqtt from '../common/mqtt'

export default class ChatPage extends Component {
    componentDidMount() {
        this.msgListener = DeviceEventEmitter.addListener('IM',(listenerMsg) => {
           if(this.state.token!=''){
               this.getInfo()
           }
        });
        this._loadInitialState().done();
    }
    componentWillUnmount() {
        this.msgListener&&this.msgListener.remove();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>{this.getInfo()});
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/IM/selectCustomerMessageList',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status===0){
                    this.setState({
                        refreshing:false,
                        data:responseJson.data
                    })
                }else{
                    this.setState({
                        refreshing:false,
                    })
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                this.setState({
                    refreshing:false,
                })
                ModalIndicator.hide();
                Toast.message(error);
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            token:'',
            data:[],
            refreshing:false
        }
    };

    complete=()=>{
        this.showPop();
    };

    _middleView=()=>{
      return <View style={{height:10,width:width}}/>
    };

    showPop=()=>{
        let overlayView = (
            <Overlay.PopView
                style={{alignItems: 'center', justifyContent: 'center'}}
                type={'zoomIn'}
                modal={true}
                ref={v => this.overlayOrderPopView = v}>
                <OverlaySureRemind
                    deleteOrder={()=>{
                        let params={
                            "token":this.state.token,
                        };
                        ModalIndicator.show("正在请求数据......");
                        fetch(Config.baseApi+'/user/loginOut',{
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: Utils.getParamsString(params)
                        })
                            .then((response) => response.json())
                            .then((responseJson) => {
                                ModalIndicator.hide();
                                if(responseJson.status===0){
                                    mqttChat(responseJson.data.id,true);
                                    this.overlayOrderPopView&&this.overlayOrderPopView.close();
                                    AsyncStorage.removeItem(STORAGE_KEY_TOKEN);
                                    Actions.reset('LoginPage')
                                }else{
                                    Toast.message(responseJson.msg);
                                }
                            })
                            .catch((error) => {
                                ModalIndicator.hide();
                                Toast.message(error);
                            });
                    }}
                    ID={this.props.ID}
                    closeOverlay={()=>{
                        this.overlayOrderPopView&&this.overlayOrderPopView.close();
                    }}
                    leftMsg={'取消'}
                    buts={'确定'}
                    text={'是否要退出'}/>
            </Overlay.PopView>);
        Overlay.show(overlayView);
    };

    onRefresh=()=>{
        this.setState({
            refreshing:true
        },()=>{
            this.getInfo()
        });
    };

    render() {
        return (
            <View style={styles.container}>
                <View style={styles.titleView}>
                    <Text style={styles.titleMsg}>聊天</Text>
                    <TouchableOpacity
                        onPress={()=>this.complete()}
                        style={styles.titleRightView}>
                        <Text style={styles.titleRightMsg}>退出</Text>
                    </TouchableOpacity>
                </View>
                <FlatList
                    ref={'list'}
                    style={{flex:1}}
                    data={this.state.data}
                    onRefresh={this.onRefresh}
                    refreshing={this.state.refreshing}
                    renderItem={(item)=><NewsChatItem
                        head={this.state.head}
                        ID={'purchaser'}
                        chatData={this.state.data}
                        callback={()=>this.getInfo(this.state.token)}
                        item={item}/>}
                    ItemSeparatorComponent={this._middleView}
                    keyExtractor={(item, index) => index}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f0f0f0'
    },
    titleView:{
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        alignItems:'center',
        justifyContent:'center',
        borderBottomWidth:0.5,
        borderColor:'#dbdbdb',
        backgroundColor:'#ffffff',
        width:width
    },
    goBackView:{
        position: 'absolute',
        left:15,
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        justifyContent:'center',
        backgroundColor:'rgba(0,0,0,0)'
    },
    titleLeftImg:{
        height:20,
        width:20
    },
    titleMsg:{
        fontSize:17,
        color:'#000'
    },
    titleRightView:{
        position: 'absolute',
        right:15,
        height:iOS?64:44,
        paddingTop:iOS?20:0,
        justifyContent:'center',
        backgroundColor:'rgba(0,0,0,0)'
    },
    titleRightMsg:{
        fontSize:17,
        color:'#000'
    }
});
